package a11_Network;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Author quan
 * @Description 客户端
 * @Date 2023/5/29 17:48
 */
public class UDPEchoClient {
    //定义一个用于客户端的DatagramSocket
    private DatagramSocket client;
    //定义服务器的端口号
    private String serverIP;
    //定义服务器的IP地址
    private int port;
    // 定义SocketAddress地址
    private SocketAddress address;

    /**
     * 构造方法：指定服务器的IP和端口号
     * @param serverIP
     * @param port
     */
    public UDPEchoClient(String serverIP,int port) throws SocketException {
        this.client = new DatagramSocket();
        this.serverIP = serverIP;
        this.port = port;
        this.address = new InetSocketAddress(serverIP,port);
    }
    public void clientStart() throws IOException {
        System.out.println("客户端已经启动");
        //循环接收用户输入
        Scanner sc = new Scanner(System.in);
        while (true){
            System.out.println("->");
            /**
             * 获取用户输入的内容并发送给服务器；然后获取服务器返回的内容并解析
             */
            String userRequest = sc.nextLine();
            //1、将用户输入的请求包装成DatagramPacket
            DatagramPacket userRequestPacket = new DatagramPacket(userRequest.getBytes(StandardCharsets.UTF_8),
                    userRequest.getBytes().length,
                    address);
            //2、发送数据
            client.send(userRequestPacket);
            //3、接收响应
            DatagramPacket respondPacket = new DatagramPacket(new byte[1024],1024);
            //4、在receive方法中填充响应数据
            client.receive(respondPacket);
            //5、解析响应数据
            String respond = new String(respondPacket.getData(),0,respondPacket.getLength(),"UTF-8");
            //打印日志
            System.out.printf("request: %s, response: %s.\n", userRequest, respond);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient client = new UDPEchoClient("127.0.0.1",9999);
        //启动客户端
        client.clientStart();
    }
}
